package com.hh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.entity.domain.SysLog;
import com.hh.entity.dto.syslog.SysLogQueryRequest;
import com.hh.mapper.SysLogMapper;
import com.hh.service.SysLogService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author hanhui
 * @description 针对表【sys_log(操作日志表：记录用户关键操作，用于审计和追溯)】的数据库操作Service实现
 * @createDate 2025-09-14 21:03:19
 */
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog>
        implements SysLogService {
    @Override
    public QueryWrapper<SysLog> getQueryWrapper(SysLogQueryRequest sysLogQueryRequest) {
        String username = sysLogQueryRequest.getUsername();
        String operation = sysLogQueryRequest.getOperation();
        String method = sysLogQueryRequest.getMethod();
        String params = sysLogQueryRequest.getParams();
        String ip = sysLogQueryRequest.getIp();
        Date createTime = sysLogQueryRequest.getCreateTime();
        int pageSize = sysLogQueryRequest.getPageSize();
        int pageNum = sysLogQueryRequest.getPageNum();
        String sortField = sysLogQueryRequest.getSortField();
        String sortOrder = sysLogQueryRequest.getSortOrder();

        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(username != null, "username", username);
        queryWrapper.like(operation != null, "operation", operation);
        queryWrapper.like(method != null, "method", method);
        queryWrapper.like(params != null, "params", params);
        queryWrapper.like(ip != null, "ip", ip);
        if (createTime!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            queryWrapper.gtSql("create_time", "'" + sdf.format(createTime) + "'");
        }

        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }
}